How to set focus on the input field in AngularJS form?
How to set focus on input field in AngularJS?
174
17-Jun-2024
Updated on 17-Jun-2024
Ashutosh Kumar Verma
17-Jun-2024Set focus on input field
In AngularJS, you can set the focus to the input field programmatically or directly in your controller's logic through a directive. Here’s how you can do this.
Using a Directive (recommended method)
Define a Directive
Create a custom directive to control set focus on each element.
Apply the Directive in HTML
Apply the
focusMe
directive to your input field. The instruction requires a scope variable (focusInput
) and will set focus on the element when the variable is true.Set Focus in Controller
In your controller, set the
focusInput
variable totrue
to trigger focus on the input field.Example-
In the example above
Directive (focusMe)
focusMe
directive checks the focusInput value using$watch
.$timeout
to delay the focus operation until after the current digestion cycle.element[0].focus()
is used to focus on the first element of the element in the reference.HTML Usage
focus-me="focusInput"
attribute of the<input>
element binds the directive to the focusInput scope variable.Controller logic
focusInput
variable.focusInput
totrue
when a condition is satisfied (e.g., after a button is pressed, at startup, etc.).Also, Read: "this" vs $scope in AngularJS controllers